package com.itheima.service.impl;

import com.itheima.dao.ContactDao;
import com.itheima.dao.impl.ContactImpl;
import com.itheima.domain.Contact;
import com.itheima.domain.ContactCondition;
import com.itheima.domain.Page;
import com.itheima.service.ContactService;

import java.sql.SQLException;
import java.util.List;

public class ContactServiceImpl implements ContactService {
    ContactDao contactDao = new ContactImpl();

    @Override
    public List<Contact> queryAll() {
        try {
            return contactDao.queryAll();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public boolean add(Contact con) {
        int add = 0;
        try {
            add = contactDao.add(con);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return add > 0;
    }

    @Override
    public Contact queryById(int id) {
        Contact contact = null;
        try {
            contact = contactDao.queryById(id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return contact;
    }

    @Override
    public boolean update(Contact contact) {
        int i = 0;
        try {
            i = contactDao.update(contact);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return i != 0;
    }

    @Override
    public boolean delete(int id) {
        int i = 0;
        try {
            i = contactDao.delete(id);

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return i != 0;
    }

    @Override
    public Page<Contact> page(int pageNo, int pageSize) {
        Page<Contact> page = new Page<>();

        page.setPageNo(pageNo);
        page.setPageSize(pageSize);

        try {
            Integer pageTotalCount = contactDao.queryForPageTotalCount();
            page.setPageTotalCount(pageTotalCount);

            Integer pageTotal = pageTotalCount / pageSize;

            if (pageTotalCount % pageSize > 0) {
                pageTotal++;
            }
            page.setPageTotal(pageTotal);

            int begin = (page.getPageNo() - 1) * pageSize;

            List<Contact> contacts = contactDao.queryForPageItems(begin, pageSize);

            page.setItems(contacts);
            return page;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<Contact> queryForCondition(ContactCondition contactCondition) {
        try {
            return contactDao.queryForCondition(contactCondition);
        } catch (SQLException e) {

        }
        return null;
    }
}
